﻿using System.Web.Http;
using System;
using Models.Responses;
using Models.Requests;
using System.Collections.Generic;
using System.Data.SqlClient;
using DataAccess;
using Models.Models;
using System.Data;
using WebApi.Classes;

namespace WebApi.Controllers
{
    public class AccountController : ApiController
    {
        [AllowAnonymous]
        [HttpGet]
        public string Index()
        {
            return "Account Controller";
        }
        
        [HttpPost]
        public UserResponse ValidateUser(LoginRequest request)
        {
            UserResponse response = new UserResponse();

            try
            {
                List<SqlParameter> parameters = new List<SqlParameter>();
                parameters.Add(new SqlParameter("szUserEmail", request.Login.UserEmail));
                parameters.Add(new SqlParameter("szPassword", request.Login.Password));
                parameters.Add(new SqlParameter("biUserID", 0) { Direction = System.Data.ParameterDirection.Output });
                parameters.Add(new SqlParameter("szSecureQuestion", string.Empty) { Direction = System.Data.ParameterDirection.Output, Size = 512 });

                Statics.AddDebugParameters(parameters);

                var result = new DataSource().Execute("svc.uspValidateLogin", parameters);

                Statics.FetchDebugParameters((BaseResponse)response, result);

                response.User = new User() { UserID = Convert.ToInt64(result.Parameters["biUserID"].Value), UserEmail = request.Login.UserEmail, SecureQuestion = result.Parameters["szSecureQuestion"].Value.ToString() };
            }
            catch (Exception ex)
            {
                response.Exception = ex;
            }

            return response;
        }

        [HttpPost]
        public SuccessFailResponse ValidateSecureAnswer(PasswordReminderRequest request)
        {
            SuccessFailResponse response = new SuccessFailResponse();

            try
            {
                List<SqlParameter> parameters = new List<SqlParameter>();
                parameters.Add(new SqlParameter("szUserEmail", request.PasswordReminder.UserEmail));
                parameters.Add(new SqlParameter("szSecureAnswer", request.PasswordReminder.SecureAnswer));

                Statics.AddDebugParameters(parameters);

                var result = new DataSource().Execute("svc.uspValidateSecureAnswer", parameters);

                Statics.FetchDebugParameters((BaseResponse)response, result);

                if (response.ErrorNumber == 0)
                {
                    response.IsSuccessful = true;
                }
            }
            catch (Exception ex)
            {
                response.Exception = ex;
            }

            return response;
        }

        [HttpPost]
        public UserMenuResponse GetMenuOptions(UserRequest request)
        {
            UserMenuResponse response = new UserMenuResponse() { UserPermissions = new UserPermissions() { User = new User(), Menu = new List<MenuItem>() }};

            try
            {
                List<SqlParameter> parameters = new List<SqlParameter>();
                parameters.Add(new SqlParameter("biUserID", request.User.UserID));

                Statics.AddDebugParameters(parameters);

                var result = new DataSource().ExecuteDataSet("svc.uspUserGetMenuOptions", parameters);

                if (result.DataSet != null && result.DataSet.Tables.Count > 0 && result.DataSet.Tables[0].Rows.Count > 0)
                {
                    response.UserPermissions.User = new Models.Models.User()
                        {
                            UserID = Convert.ToInt64(result.DataSet.Tables[0].Rows[0]["UserID"]),
                            FirstName = result.DataSet.Tables[0].Rows[0]["FirstName"].ToString(),
                            LastName = result.DataSet.Tables[0].Rows[0]["LastName"].ToString(),
                            UserEmail = result.DataSet.Tables[0].Rows[0]["UserEmail"].ToString(),
                            StoreID = Convert.ToInt64(result.DataSet.Tables[0].Rows[0]["StoreID"]),
                            SecureQuestion = result.DataSet.Tables[0].Rows[0]["SecureQuestion"].ToString(),
                            EmailAlertRecipient = Convert.ToBoolean(result.DataSet.Tables[0].Rows[0]["EmailAlertRecipient"]),
                            BillingReportRecipient = Convert.ToBoolean(result.DataSet.Tables[0].Rows[0]["BillingReportRecipient"]),
                            RevokeStatus = Convert.ToBoolean(result.DataSet.Tables[0].Rows[0]["RevokeStatus"]),
                            ppjStoreID = Convert.ToInt64(result.DataSet.Tables[0].Rows[0]["PPJStoreID"])
                        };
                }

                if (result.DataSet != null && result.DataSet.Tables[1] != null && result.DataSet.Tables[1].Rows.Count > 0)
                {
                    foreach (DataRow row in result.DataSet.Tables[1].Rows)
                    {
                        response.UserPermissions.Menu.Add(new MenuItem()
                            {
                                ID = Convert.ToInt32(row["UserMenuID"]),
                                AppID = Convert.ToInt32(row["AppMenuID"]),
                                ParentID = Convert.ToInt32(row["ParentID"]),
                                Name = row["MenuName"].ToString(),
                                UserRights = row["UserRights"].ToString(),
                                Path = row["PageLocation"].ToString(),
                                RNumber = row["RNumber"].ToString()
                            });
                    }
                }

                Statics.FetchDebugParameters((BaseResponse)response, result);
            }
            catch (Exception ex)
            {
                response.Exception = ex;
            }

            return response;
        }

        [HttpPost]
        public SuccessFailResponse ChangePassword(ChangePasswordRequest request)
        {
            SuccessFailResponse response = new SuccessFailResponse();

            try
            {
                List<SqlParameter> parameters = new List<SqlParameter>();
                parameters.Add(new SqlParameter("biUserID", request.ChangePassword.UserID));
                parameters.Add(new SqlParameter("szPasswordOld", request.ChangePassword.OldPassword));
                parameters.Add(new SqlParameter("szPassword", request.ChangePassword.NewPassword));
                parameters.Add(new SqlParameter("szSecureQuestion", request.ChangePassword.SecureQuestion));
                parameters.Add(new SqlParameter("szSecureAnswer", request.ChangePassword.SecureAnswer));

                Statics.AddDebugParameters(parameters);

                var result = new DataSource().Execute("svc.uspUserChangePassword", parameters);

                Statics.FetchDebugParameters((BaseResponse)response, result);

                if (response.ErrorNumber == 0)
                {
                    response.IsSuccessful = true;
                }
            }
            catch (Exception ex)
            {
                response.Exception = ex;
            }

            return response;
        }

        [HttpPost]
        public SuccessFailResponse ChangeUserStatus(UserRequest request)
        {
            SuccessFailResponse response = new SuccessFailResponse();

            try
            {
                List<SqlParameter> parameters = new List<SqlParameter>();
                parameters.Add(new SqlParameter("biUserID", request.User.UserID));
                parameters.Add(new SqlParameter("@bRevokeStatus", request.User.RevokeStatus));
                parameters.Add(new SqlParameter("biUpdUser", request.User.UserUpdated));

                Statics.AddDebugParameters(parameters);

                var result = new DataSource().Execute("svc.uspUserChangeStatus", parameters);

                Statics.FetchDebugParameters((BaseResponse)response, result);

                if (response.ErrorNumber == 0)
                {
                    response.IsSuccessful = true;
                }
            }
            catch (Exception ex)
            {
                response.Exception = ex;
            }

            return response;
        }

        [HttpPost]
        public SuccessFailResponse UpdateUser(UserRequest request)
        {
            SuccessFailResponse response = new SuccessFailResponse();

            try
            {
                List<SqlParameter> parameters = new List<SqlParameter>();
                parameters.Add(new SqlParameter("biUserID", request.User.UserID));
                parameters.Add(new SqlParameter("biStoreID", request.User.StoreID));
                parameters.Add(new SqlParameter("szFirstName", request.User.FirstName));
                parameters.Add(new SqlParameter("szLastName", request.User.LastName));
                parameters.Add(new SqlParameter("szUserEmail", request.User.UserEmail));
                parameters.Add(new SqlParameter("bEmailAlertRecipient", request.User.EmailAlertRecipient));
                parameters.Add(new SqlParameter("bBillingReportRecipient", request.User.BillingReportRecipient));
                parameters.Add(new SqlParameter("biUpdUser", request.User.UserUpdated));

                Statics.AddDebugParameters(parameters);

                var result = new DataSource().Execute("svc.uspUserUpdate", parameters);

                if (response.ErrorNumber == 0)
                {
                    response.IsSuccessful = true;
                }

                Statics.FetchDebugParameters((BaseResponse)response, result);
            }
            catch (Exception ex)
            {
                response.Exception = ex;
            }

            return response;
        }

        [HttpPost]
        public UserListResponse GetUserListByStore(UserListRequest request)
        {
            UserListResponse response = new UserListResponse() { UserList = new UserList() { List = new List<User>() } };

            try
            {
                List<SqlParameter> parameters = new List<SqlParameter>();
                parameters.Add(new SqlParameter("biStoreID", request.StoreID));
                parameters.Add(new SqlParameter("iPageIndex", request.PageIndex));
                parameters.Add(new SqlParameter("iPageSize", request.PageSize));
                parameters.Add(new SqlParameter("szSortColumn", request.SortColumn));
                parameters.Add(new SqlParameter("szSortDirection", request.SortDirection));
                parameters.Add(new SqlParameter("bHideRevoked", request.HideRevoked));
                parameters.Add(new SqlParameter("biResultCount", 0) { Direction = ParameterDirection.Output });

                Statics.AddDebugParameters(parameters);

                var result = new DataSource().ExecuteDataSet("svc.uspGetStoreUsersList", parameters);

                if (result.DataSet != null && result.DataSet.Tables.Count > 0 && result.DataSet.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow row in result.DataSet.Tables[0].Rows)
                    {
                        response.UserList.List.Add(new User()
                            {
                                UserID = Convert.ToInt64(row["UserID"]),
                                FirstName = row["FirstName"].ToString(),
                                LastName = row["LastName"].ToString(),
                                UserEmail = row["UserEmail"].ToString(),
                                DateLastLogin = (row["DateLastLogin"] == DBNull.Value ? null : (DateTime?)Convert.ToDateTime(row["DateLastLogin"])),
                                EmailAlertRecipient = Convert.ToBoolean(row["EmailAlertRecipient"]),
                                BillingReportRecipient = Convert.ToBoolean(row["BillingReportRecipient"]),
                                ResetPassword = Convert.ToBoolean(row["ResetPassword"]),
                                RevokeStatus = Convert.ToBoolean(row["RevokeStatus"]),
                                DateRevoked = (row["DateRevoked"] == DBNull.Value ? null : (DateTime?)Convert.ToDateTime(row["DateRevoked"])),
                                DateUpdated = (row["DateUpdated"] == DBNull.Value ? null : (DateTime?)Convert.ToDateTime(row["DateUpdated"]))
                            });
                    }
                }

                response.UserList.PageIndex = request.PageIndex;
                response.UserList.PageSize = request.PageSize;
                response.UserList.SortColumn = request.SortColumn;
                response.UserList.SortDirection = request.SortDirection;
                response.UserList.ResultCount = Convert.ToInt64(result.Parameters["biResultCount"].Value);

                Statics.FetchDebugParameters((BaseResponse)response, result);
            }
            catch (Exception ex)
            {
                response.Exception = ex;
            }

            return response;
        }

        [HttpPost]
        public SuccessFailResponse UpdateMenuOptions(MenuItemRequest request)
        {
            SuccessFailResponse response = new SuccessFailResponse();

            try
            {
                foreach (var option in request.Menu.List)
                {
                    List<SqlParameter> parameters = new List<SqlParameter>();
                    parameters.Add(new SqlParameter("biUserMenuID", option.ID));
                    parameters.Add(new SqlParameter("iStatus", option.Status));
                    parameters.Add(new SqlParameter("biUpdUser", request.UserUpdated));

                    Statics.AddDebugParameters(parameters);

                    var result = new DataSource().Execute("svc.uspUserMenuRecordUpdate", parameters);

                    Statics.FetchDebugParameters((BaseResponse)response, result);

                    if (response.ErrorNumber == 0)
                    {
                        response.IsSuccessful = true;
                    }
                }
            }
            catch (Exception ex)
            {
                response.Exception = ex;
            }

            return response;
        }
    }
}
